Popular Searches
Popular Course Categories
Popular Courses

Component Composition

Component Composition

React Components

Component Composition in React JS – Detailed Notes

Component Composition is an important concept in React JS that involves combining smaller, independent components to build larger and more complex user interfaces. Instead of creating one large component for an entire application, developers combine reusable components such as headers, buttons, cards, navigation bars, and forms.

Component composition helps improve code reusability, maintainability, readability, and flexibility in React applications.

Explore the JustAcademy React JS Training Course or Register for React JS Course Demo.


1. What Is Component Composition?

Component Composition is the process of building a user interface by combining multiple smaller React components. Each component handles a particular part of the interface, and parent components arrange those components to create the complete UI.

For example, an e-commerce website may contain a Header, Navbar, ProductList, ProductCard, ShoppingCart, and Footer. These components can be combined inside a parent component to build the page.

Example

function Header() {
  return <h1>My Website</h1>;
}
function Content() {
  return <p>Welcome to my website!</p>;
}
function Footer() {
  return <footer>Copyright 2026</footer>;
}
function App() {
  return (
    <div>
      <Header />
      <Content />
      <Footer />
    </div>
  );
}
export default App;

Explanation: The App component combines three smaller components: Header, Content, and Footer. This is a basic example of component composition.


2. Why Is Component Composition Important?

  • Reusability: Components can be used in different pages or sections.
  • Maintainability: Smaller components are easier to update and manage.
  • Readability: The application structure becomes easier to understand.
  • Flexibility: Components can be combined in different ways.
  • Separation of concerns: Each component can focus on a particular responsibility.
  • Scalability: New features can be created by combining existing components.
  • Testing: Individual components can often be tested independently.

3. Understanding Parent and Child Components

In component composition, one component can render another component. The component that renders another component is commonly called the parent, while the rendered component is called the child.

Example

function Message() {
  return <p>Learn React step by step.</p>;
}
function Dashboard() {
  return (
    <section>
      <h1>Dashboard</h1>
      <Message />
    </section>
  );
}
export default Dashboard;

Explanation: Dashboard is the parent component and Message is its child. The parent composes the child into its UI.


4. Component Composition Using JSX

JSX allows developers to place React components inside other components using component tags. This is the most common way to compose a React interface.

Syntax

function ParentComponent() {
  return (
    <div>
      <ChildComponent />
    </div>
  );
}

Example

function Navbar() {
  return <nav>Home | About | Contact</nav>;
}
function MainContent() {
  return <main>Welcome to our application.</main>;
}
function App() {
  return (
    <div>
      <Navbar />
      <MainContent />
    </div>
  );
}
export default App;

Here, App combines the navigation and main content components to create the overall page structure.


5. Component Composition Using Props

Props allow parent components to pass information to child components. By combining composition and props, the same child component can display different content in different places.

Example

function UserCard({ name, role }) {
  return (
    <div className="user-card">
      <h2>{name}</h2>
      <p>Role: {role}</p>
    </div>
  );
}
function App() {
  return (
    <div>
      <UserCard name="Aarav" role="Developer" />
      <UserCard name="Priya" role="Designer" />
    </div>
  );
}
export default App;

Explanation: The parent component renders the same UserCard component twice with different props. Each instance displays different information.


6. Composition Using the children Prop

The children prop is one of the most useful patterns for component composition. JSX placed between a component's opening and closing tags is passed to that component as children.

This approach is useful when creating reusable containers, cards, panels, layouts, and modal structures.

Example

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}
function App() {
  return (
    <div>
      <Card>
        <h2>React JS</h2>
        <p>Learn component composition.</p>
      </Card>
      <Card>
        <h2>JavaScript</h2>
        <p>Learn the fundamentals of JavaScript.</p>
      </Card>
    </div>
  );
}
export default App;

Explanation: The Card component provides the common wrapper, while the parent supplies different content for each card through children.

Benefits of the children prop

  • Allows flexible nested content.
  • Reduces duplicated wrapper markup.
  • Helps create reusable layouts and containers.
  • Separates the container's structure from its content.

7. Passing Different JSX Elements Through Props

Sometimes a component needs separate content areas, such as a header, body, and footer. You can pass JSX elements through named props to customize each area.

Example

function PageLayout({ header, content, footer }) {
  return (
    <div className="page-layout">
      <header>{header}</header>
      <main>{content}</main>
      <footer>{footer}</footer>
    </div>
  );
}
function App() {
  return (
    <PageLayout
      header={<h1>Student Portal</h1>}
      content={<p>Welcome to your dashboard.</p>}
      footer={<small>Student Services</small>}
    />
  );
}
export default App;

Explanation: The parent supplies different JSX elements to the PageLayout component. The layout decides where to display each element.


8. Component Composition with Lists

Composition can be combined with JavaScript's map() method to display multiple instances of a reusable component.

Example

const courses = [
  { id: 1, title: "React JS", duration: "8 Weeks" },
  { id: 2, title: "Flutter", duration: "10 Weeks" },
  { id: 3, title: "Selenium", duration: "6 Weeks" }
];
function CourseCard({ title, duration }) {
  return (
    <article>
      <h2>{title}</h2>
      <p>Duration: {duration}</p>
    </article>
  );
}
function CourseList() {
  return (
    <div>
      {courses.map((course) => (
        <CourseCard
          key={course.id}
          title={course.title}
          duration={course.duration}
        />
      ))}
    </div>
  );
}
export default CourseList;

Explanation: CourseList composes several CourseCard instances. Each card receives its own data through props, and the stable key helps React identify the list item.


9. Component Composition with Conditional Rendering

A parent component can decide which child component to render based on a condition. This makes composition useful for dashboards, authentication screens, and status messages.

Example

function LoginMessage() {
  return <p>Please log in to continue.</p>;
}
function WelcomeMessage() {
  return <p>Welcome back!</p>;
}
function App({ isLoggedIn }) {
  return (
    <div>
      <h1>User Portal</h1>
      {isLoggedIn ? <WelcomeMessage /> : <LoginMessage />}
    </div>
  );
}
export default App;

Explanation: The parent renders a different child component depending on the value of isLoggedIn.


10. Organizing Composed Components into Separate Files

In larger React applications, components can be stored in separate files and imported into parent components. This makes the project easier to navigate.

Example folder structure

src/
├── components/
│   ├── Header.jsx
│   ├── Footer.jsx
│   ├── CourseCard.jsx
│   └── PageLayout.jsx
├── pages/
│   └── CoursesPage.jsx
├── App.jsx
└── main.jsx

Header.jsx

export default function Header() {
  return <header><h1>Learning Hub</h1></header>;
}

Footer.jsx

export default function Footer() {
  return <footer>Keep Learning!</footer>;
}

App.jsx

import Header from "./components/Header.jsx";
import Footer from "./components/Footer.jsx";

export default function App() {
  return (
    <div>
      <Header />
      <main>Welcome to the Learning Hub.</main>
      <Footer />
    </div>
  );
}

Explanation: The App component imports and combines components defined in separate files. The example demonstrates how composition works across a project structure.


11. Component Composition vs. Inheritance

React encourages composition as a common way to reuse and organize UI behavior. Instead of relying on class inheritance to share UI structure, developers typically combine components and pass props or nested JSX.

Component composition Inheritance
Combines components to build interfaces. Creates a class based on another class.
Commonly uses JSX, props, and children. Uses class inheritance mechanisms.
Supports flexible combinations of UI elements. Can create tighter relationships between class types.
Is a common React UI reuse pattern. Is not the usual recommendation for sharing UI behavior in React.

Important: This comparison refers to UI reuse. JavaScript inheritance still exists, and React supports class components, but composition is generally preferred for assembling React interfaces.


12. Component Composition vs. Reusable Components

Reusable components Component composition
Focuses on creating components that can be used repeatedly. Focuses on combining components to create a larger interface.
Example: a reusable Button. Example: combining Header, Button, and Footer in a page.
Often uses props to customize an element. Often uses JSX nesting, props, and children.
Reduces duplicated UI implementation. Organizes smaller components into a complete UI.

13. Best Practices for Component Composition

  • Keep components focused: Each component should have a clear responsibility.
  • Prefer composition for UI reuse: Combine components rather than creating complex inheritance hierarchies.
  • Use props for data: Pass information explicitly to child components.
  • Use children for flexible content: Make wrappers and layout components adaptable.
  • Keep component definitions at the top level: Avoid defining component functions inside other components because their identity can change between renders.
  • Use stable keys for lists: Provide unique keys when rendering arrays of components.
  • Avoid excessive prop forwarding: Pass only the values a child component needs unless forwarding props is intentional.
  • Do not call components as ordinary functions: Render them with JSX, such as
    .
  • Keep props read-only: Do not mutate values received from a parent.
  • Avoid unnecessary abstraction: Compose components when it improves clarity or reuse, not merely to split every line of JSX.
  • Use semantic HTML: Choose suitable elements such as header, main, nav, and footer.

14. Common Mistakes in Component Composition

Mistake Correct approach
Repeating the same JSX in several places. Extract a shared component when it improves clarity and maintainability.
Passing data through hardcoded values everywhere. Use props for values that vary.
Forgetting to render children. Include {children} where the nested content should appear.
Using array indexes as keys when stable IDs are available. Use stable, unique IDs for list keys.
Defining a component inside another component. Move the nested component definition to the top level when it is a React component.
Calling a component directly as a function. Render the component through JSX.
Creating overly complicated parent components. Divide the interface into logical child components.
Passing too many unrelated props. Review the component's responsibility and consider composition or a simpler API.

15. Practical Project: Course Website Using Component Composition

Project objective: Build a simple course website by combining reusable components. The page will include a header, course cards, and a footer.

CourseCard.jsx

export default function CourseCard({ title, duration, level }) {
  return (
    <article className="course-card">
      <h2>{title}</h2>
      <p>Duration: {duration}</p>
      <p>Level: {level}</p>
      <button type="button">Explore Course</button>
    </article>
  );
}

Header.jsx

export default function Header() {
  return (
    <header>
      <h1>My Learning Hub</h1>
      <p>Explore courses and develop new skills.</p>
    </header>
  );
}

Footer.jsx

export default function Footer() {
  return <footer>Happy Learning!</footer>;
}

App.jsx

import Header from "./components/Header.jsx";
import Footer from "./components/Footer.jsx";
import CourseCard from "./components/CourseCard.jsx";

const courses = [
  { id: 1, title: "React JS", duration: "8 Weeks", level: "Beginner" },
  { id: 2, title: "Flutter", duration: "10 Weeks", level: "Intermediate" },
  { id: 3, title: "Selenium", duration: "6 Weeks", level: "Beginner" }
];

export default function App() {
  return (
    <div>
      <Header />
      <main>
        <h2>Available Courses</h2>
        <div className="course-list">
          {courses.map((course) => (
            <CourseCard
              key={course.id}
              title={course.title}
              duration={course.duration}
              level={course.level}
            />
          ))}
        </div>
      </main>
      <Footer />
    </div>
  );
}

Optional CSS

.course-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}
.course-card {
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
}
.course-card button {
  padding: 8px 12px;
  cursor: pointer;
}

What you learn from this project:

  • How to combine multiple components into one page.
  • How to pass data using props.
  • How to create reusable course cards.
  • How to render multiple components using map().
  • How to use stable keys for list items.
  • How to organize code into separate component files.

16. Interview Questions and Answers

Q1. What is component composition in React?

Answer: Component composition is the process of combining smaller React components to build larger user interfaces.

Q2. Why is component composition used?

Answer: It improves code reuse, readability, flexibility, maintainability, and separation of concerns.

Q3. What is the role of a parent component?

Answer: A parent component can arrange child components, pass props to them, and determine how they fit into the interface.

Q4. What is the children prop?

Answer: The children prop contains the content nested between a component's opening and closing JSX tags.

Q5. How can props help in component composition?

Answer: Props allow parent components to pass data, callbacks, and JSX elements to child components.

Q6. What is the difference between composition and inheritance?

Answer: Composition builds interfaces by combining components. Inheritance creates a class based on another class. Composition is generally preferred for React UI reuse.

Q7. Can one component contain multiple child components?

Answer: Yes. A parent component can render many children in its JSX.

Q8. Can JSX be passed through props?

Answer: Yes. JSX elements can be passed through named props or supplied as nested content through children.

Q9. How does composition work with lists?

Answer: A parent can use map() to render multiple instances of a reusable child component, providing each item with a stable key.

Q10. What is a common mistake when composing components?

Answer: Common mistakes include repeating JSX unnecessarily, forgetting to render children, omitting stable list keys, or creating overly complex components.


17. Revision Checklist

  • Understand the meaning of component composition.
  • Know how parent and child components work together.
  • Practice rendering components inside other components.
  • Understand how props customize child components.
  • Use the children prop to build flexible wrappers.
  • Learn to pass JSX through named props.
  • Practice composition with lists and conditional rendering.
  • Organize components in separate files when appropriate.
  • Understand composition versus inheritance and reusable components.
  • Follow best practices for component structure and stable keys.

18. Official Documentation and Course Links


Conclusion

Component Composition is a fundamental React JS concept for building complete interfaces from smaller, manageable components. By using JSX, props, the children prop, and reusable components together, developers can create flexible applications that are easier to maintain and extend.

Practice composing headers, navigation bars, cards, forms, and footers to develop a strong understanding of component composition in React JS. To continue learning, visit the JustAcademy React JS Training Course or register for a React JS course demo.

whatsapp